package com.erdos.core.util.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.swing.table.TableModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
import org.dom4j.Node;

import com.erdos.common.util.itext.XmlItextConfigUtil;
import com.erdos.core.util.service.PDFService;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

public class PDFServiceImpl implements PDFService {
	private final static Log logger = LogFactory.getLog(PDFServiceImpl.class);

	public void write(String templatePDFName, String templateXMLName,
			Map<String, String> data, OutputStream outputStream, Font font) {
		PdfReader reader = null;
		try {
			reader = new PdfReader(templatePDFName);// 例c:\\mytemp\\t1.pdf
			PdfStamper stamp = new PdfStamper(reader,outputStream );
			Font fontChinese = null;
			if (font == null) {
			BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
			fontChinese = new Font(bf, 12, Font.NORMAL);
			} else {
				fontChinese = font;
			}
			AcroFields form = stamp.getAcroFields();
			List<Element> fields = getFields(templateXMLName);// 例template1
			if (fields != null && fields.size() > 0) {
				for (Element e : fields) {
					if (form.getField(e.attributeValue("value")) != null) {
						form.setFieldProperty(e.attributeValue("value"), null,
								fontChinese, null);
						form.setField(e.attributeValue("value"), data.get(e
								.attributeValue("value")));
						//logger.debug("data.get(e.attributeValue):"+data.get(e.attributeValue("value")));
					}
				}
			}
			stamp.setFormFlattening(true);
			stamp.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (DocumentException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			reader.close();
		}

	}

	public void write(String[] headers, int[] headWidths, TableModel data,
			OutputStream outputStream, Font font) {
		Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); // 定义纸张类型及方向,页边距

		// step 1

		try {
			// step 2: we set the ContentType and create an instance of the
			// corresponding Writer
			// response.setContentType("application/pdf");
			PdfWriter.getInstance(document, outputStream);//
			// step3
			document.open();

			BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					BaseFont.NOT_EMBEDDED);
			Font fontChinese = new Font(bf, 12, Font.NORMAL);
			if (font != null) {
				fontChinese = font;
			}
			// step4 定义表格填充内容
			// String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD",
			// "119000", "96 06", "2001-08-13", "4350", "6011648299",
			// "FLFLMTGP", "153", "119000.00" };
			int NumColumns = headers.length; // 定义表格列数

			PdfPTable datatable = new PdfPTable(NumColumns); // 创建新表.

			// int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 };
			// // percentage
			if(headWidths!=null&&headWidths.length>0){
			int[] headerwidths = headWidths; // 定义表格头宽度
			datatable.setWidths(headerwidths);
			}
			datatable.setWidthPercentage(100); // percentage
			datatable.getDefaultCell().setPadding(3);
			datatable.getDefaultCell().setBorderWidth(2);
			datatable.getDefaultCell().setHorizontalAlignment(
					com.lowagie.text.Element.ALIGN_CENTER);
			// datatable.getDefaultCell().set
			// 以下是填充表头
			// datatable.a
			for (int i = 0; i < headers.length; i++) {
				datatable.addCell(new Paragraph(headers[i], fontChinese));
			}
			datatable.setHeaderRows(1); // this is the end of the table header

			datatable.getDefaultCell().setBorderWidth(1);
			for (int i = 0; i <data.getRowCount(); i++) {
				if (i % 2 != 1) {
					datatable.getDefaultCell().setGrayFill(1.0f);
				}
				for (int j = 0; j < headers.length; j++) {
					datatable.addCell(new Paragraph((String) data.getValueAt(i,
							j), fontChinese));
					//logger.debug("data.getValueAt(i,j)"+data.getValueAt(i,j));
				}
				if (i % 2 != 1) {
					datatable.getDefaultCell().setGrayFill(0.8f);
				}
			}
			document.add(datatable); // 加载新表
		} catch (DocumentException de) {
			de.printStackTrace();
			System.err.println("document: " + de.getMessage());
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// step 5: we close the document (the outputstream is also closed
			// internally)
			document.close();
		}

	}

	/**
	 * 根据template Name取得fields
	 * @param templateName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<Element> getFields(String templateName) {
		List<Node> elements = XmlItextConfigUtil.getElements("//template",
				"itextConfigExample.xml");
		for (Node a : elements) {
			Element ele = (Element) a;
			if (templateName.equals(ele.attributeValue("name"))) {
				List<Element> fields = ele.elements("field");
				logger.debug("fields:" + fields.size());
				return fields;
			}

			ele.attributeValue("name");
			logger.debug("ele:" + ele.attributeValue("name"));
		}
		logger.debug("elements:" + elements.size());
		return null;
	}

}
